// 每个依赖下的issue
import React from 'react';
import ListLoading from 'atComponents/ListLoading';
import { YunxiaoIcon, Title } from '@alife/devops-ui';
import PathEllipsis from 'components/pathEllipsis';
import DetailItem from './detailItem';
import exceed from 'utils/apimap';
import { getPathWithRootPath } from 'utils/router';
import { Button } from '@teamix/ui';
import intl from '../../locale';

const prefix = 'dependency-build-issue-list-item';
export default class Item extends React.Component {
  state = {
    isLoading: false,
    issue_list: [],
  };

  componentDidMount() {
    const { forceUpdateDialog } = this.props;
    this.getIssueList(forceUpdateDialog);
  }

  // 通过所有的issues内容
  getIssueList = (cb) => {
    const { detail, build, projectId } = this.props;
    const { issue_id_list } = detail;

    const buildId = build.id;

    const issue_id_length = issue_id_list.length;

    const list_of_issue_ids = [];
    let batch_size;

    if (issue_id_length > 50) {
      // issue大于50分批查询
      batch_size = Math.ceil(issue_id_length / 50);
      for (let i = 0; i < batch_size; i++) {
        list_of_issue_ids[i] = issue_id_list.slice(50 * i, Math.min(50 * (i + 1), issue_id_length));
      }

      for (let i = 0; i < batch_size; i++) {
        const ids = list_of_issue_ids[i].join(',');
        exceed
          .fetch({
            api: 'projects.builds.issues.batch',
            params: { projectId: projectId || window.FORCE.pathResource.id, buildId },
            data: {
              issue_ids: ids,
            },
          })
          .then((result) => {
            result.shift();
            this.setState({
              issue_list: [...this.state.issue_list, ...result],
              isLoading: false,
            });

            cb && cb();
          })
          .fail(console.log);
      }
    } else {
      exceed
        .fetch({
          api: 'projects.builds.issues.batch',
          params: { projectId: projectId || window.FORCE.pathResource.id, buildId },
          data: {
            issue_ids: issue_id_list.join(','),
          },
        })
        .then((result) => {
          result.shift();
          this.setState({
            issue_list: result,
            isLoading: false,
          });

          cb && cb();
        })
        .fail(console.log);
    }
  };

  render() {
    const { detail, issueFilter } = this.props;
    const { issue_list, isLoading } = this.state;
    const { pathResource, resourceSubject } = window.FORCE;
    const cur_issue_list = issue_list.filter((item) => {
      return !issueFilter || item.level.toLowerCase() === issueFilter;
    });
    return (
      <div>
        {isLoading ? (
          <ListLoading />
        ) : (
          <div className={prefix}>
            <div>
              {detail.suggestion ? (
                <div className={`${prefix}-suggestion`}>
                  <div className={`${prefix}-suggestion-icon`}>
                    <YunxiaoIcon type="resource-pool-line" />
                  </div>
                  <div className={`${prefix}-suggestion-content`}>
                    <div className="title">
                      {intl.get({
                        id: 'code-assets.components.dependencyBuildResultIssues.listItem.RecommendedSolutions',
                        defaultMessage: '推荐修复方案',
                      })}
                    </div>
                    <div className={`suggestion ${detail.build_patch_id ? 'has-btn' : ''}`}>
                      <Title align="t" trigger={<span>{detail.suggestion}</span>}>
                        {detail.suggestion}
                      </Title>
                    </div>
                    {detail.build_patch_id && (
                      <Button
                        type="text"
                        component="a"
                        target="_blank"
                        href={getPathWithRootPath(`/${pathResource.fullPath}/project_security/dependency_analysis/${resourceSubject.revision}?auto_open_issue_id=${detail.parent_issue_id}`)}
                        size="xs"
                        className="go-fix-detail"
                      >
                        {intl.get({
                          id: 'code-assets.components.dependencyBuildResultIssues.listItem.GoToAutomaticRepair',
                          defaultMessage: '前往自动修复',
                        })}
                      </Button>
                    )}
                  </div>
                </div>
              ) : null}

              <div className={`${prefix}-file`}>
                <div className={`${prefix}-file-left`}>
                  {intl.get({
                    id: 'code-assets.components.dependencyBuildResultIssues.listItem.File',
                    defaultMessage: '所属文件',
                  })}
                </div>
                <div className={`${prefix}-file-right`}>
                  <PathEllipsis path={detail.file_name} />
                </div>
              </div>
              {
                <div className={`${prefix}-list`}>
                  {cur_issue_list.map((item, index) => {
                    return <DetailItem item={item} index={index} />;
                  })}
                </div>
              }
            </div>
          </div>
        )}
      </div>
    );
  }
}
